package com.qf.sercvice.impl;

import com.qf.po.Hostinfo;
import com.qf.repository.HostinfoRepository;
import com.qf.sercvice.HostinfoService;
import com.qf.utils.JsonUtil;
import com.qf.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Optional;

@Service
public class HostinfoServiceImpl implements HostinfoService {
    @Autowired
    HostinfoRepository hostinfoRepository;
    @Autowired
    RedisUtils redisUtils;

    @Override
    public List<Hostinfo> finds() {
        try {
            //从redis获取json串
            String hget = redisUtils.hget("hostinfos", "catory");
            if (!ObjectUtils.isEmpty(hget)) {
                //将json转为object
                List<Hostinfo> hostinfos = JsonUtil.jsonToList(hget, Hostinfo.class);
                return hostinfos;
            }
            List<Hostinfo> all = hostinfoRepository.findAll();
            //将对象集合转为json字符串，并存入redis中
            String json = JsonUtil.objectToJson(all);
            redisUtils.hset("hostinfos", "catory", json);
            if (all != null) {
                return all;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Hostinfo find(Integer hid) {
        Optional<Hostinfo> byId = hostinfoRepository.findById(hid);
        Hostinfo hostinfo = byId.get();
        if (hostinfo != null) {
            return hostinfo;
        }
        return null;
    }

    @Override
    public Hostinfo add(Hostinfo hostinfo) {
        Hostinfo save = hostinfoRepository.save(hostinfo);
        if (!ObjectUtils.isEmpty(save)) {
            return save;
        }
        return null;
    }

    @Override
    public Hostinfo update(Hostinfo hostinfo) {
        Hostinfo hostinfo1 = hostinfoRepository.saveAndFlush(hostinfo);
        if (!ObjectUtils.isEmpty(hostinfo1)) {
            return hostinfo1;
        }
        return null;
    }
}
